package utils

import (
	"fmt"
	"log"
	"net/http"
)

type ErrorResponse struct {
	Error string `json:"error"`
	Code  int    `json:"code"`
	Msg   string `json:"msg"`
}

func ThrowHttp(code int, msg string) {

}

// 自定义中间件，用于异常捕获和处理
func Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("Panic: %+v\n", err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}

func ErrorHandler(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 使用中间件处理next(w, r)可能发生的错误
		defer func() {
			if err := recover(); err != nil {
				log.Printf("Recovered from panic: %v", err)
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusInternalServerError)
				_, err = fmt.Fprint(w, err)
				if err != nil {
					return
				}
				//_ = json.NewEncoder(w).Encode(ErrorResponse{Error: "Internal server error"})
			}
		}()
		next.ServeHTTP(w, r)
	})
}
func main() {
	http.Handle("/", ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 故意造成一个panic，看看errorHandler是如何处理的
		panic("An unexpected error occurred")
	})))

	log.Fatal(http.ListenAndServe(":8080", nil))
}
